#/bin/python

import os

gentooTar = "/media/storage/tmp/044-gentoo/stage3-i686-20100817.tar.bz2"
portagesTar = "/media/storage/tmp/044-gentoo/portage-20100824.tar.bz2"

destDev = "/dev/sdb5"
bootDev = "/dev/sdb1"

insideGentooScript = os.path.abspath(os.path.join(".", "inside-gentoo"))

if destDev is None or bootDev is None:
	print "setup dest-dev and boot-dev"
	exit()

if gentooTar is None:
	stage3 = "stage3-i686-20100824.tar.bz2"
	gentooTarURL = "http://distfiles.gentoo.org/releases/x86/autobuilds/current-stage3/" + stage3
	os.system("wget " + gentooTarURL)
	gentooTar = os.path.abspath(os.path.join(".", stage3))

if portagesTar is None:
	ports = "portage-20100827.tar.bz2"
	portagesTarURL = "http://mirrors.kernel.org/gentoo/snapshots/" + ports
	os.system("wget " + portagesTarURL)
	portagesTar = os.path.abspath(os.path.join(".", ports))

if not os.path.exists("/mnt/gentoo"):
	os.makedirs("/mnt/gentoo")
os.system("mount " + destDev + " /mnt/gentoo")
if not os.path.exists("/mnt/gentoo/boot"):
	os.makedirs("/mnt/gentoo/boot")
os.system("mount " + bootDev + " /mnt/gentoo/boot")
os.chdir("/mnt/gentoo")

print "extracting gentoo stage 3 ..."
os.system("tar xjpf " + gentooTar)
print "extracting gentoo stage 3 ...\t\tOK"
if not os.path.exists("/mnt/gentoo/usr"):
	os.makedirs("/mnt/gentoo/usr")
os.chdir("/mnt/gentoo/usr")
print "extracting portages ..."
os.system("tar xjpf " + portagesTar)
print "extracting portages ...\t\tOK"

os.system("cp " + insideGentooScript + " /mnt/gentoo/")
os.system("chmod a+x /mnt/gentoo/inside-gentoo")
print "Chrooting ..."
os.chdir("/")
chrootcmd = """\
mount -t proc proc /mnt/gentoo/proc ; \
mount -o bind /dev /mnt/gentoo/dev ; \
cp -L /etc/resolv.conf /mnt/gentoo/etc/ ; \
chroot /mnt/gentoo /bin/bash \
"""
os.system(chrootcmd)
print "Chrooting ...\t\tOK"

